Best Time to Buy and Sell Stock


https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
if(n<2) return 0;//?为什么在循环调不出来
int cur_min=prices[0];//定义当前最小价格
int max_profit=0;
for(int i=1;i<n;i++)
{
max_profit=max(max_profit,prices[i]-cur_min);
cur_min=min(cur_min,prices[i]);
}
return max_profit;
}
};